import { FC, ReactElement, ReactNode } from "react";
import { CompProps } from "../../types/comp";
import { Button, Card, Form, Pagination, Space, Typography } from "antd";
import classNames from "classnames";
import BreadcrumbList, { BreadcrumbListProps } from "../BreadcrumbList";
import {
  ContextVal,
  SearchPageProvider,
  SearchPageProviderProps,
  useSearchPageContext,
} from "./context";
import { PaginationProps } from "rc-pagination";
import { get, replace } from "lodash";
import login from "../../pages/login";
import { cleanToken } from "../../utils/token";
import { useRouter } from "next/router";

type Props = {
  noSearch?: any
  onSearchHandle?: (params: any) => void
  breadcrumbList?: BreadcrumbListProps["list"];
  fieldMap?: Record<any, string[]>;
  onMount?: (core: ContextVal) => void;
  uploadData?: (data: any[]) => void;
  defaultPageSize?: number;
  pageSizeOptions?: number[];
  searchFormat?: (data: any) => any;
  queryMutationParams?: any
  defaultFilters?: any;
} & SearchPageProviderProps;

const SearchPage: FC<Props> & {
  Search: FC<
    CompProps & {
      extraHeader?: any;
      addLabel?: string;
      onAddClick?: () => void;
    onHandleSearch?: () => void
    }
  >;
  actions?: ReactElement[];
  Cont: FC<CompProps>;
} = (props) => {
  const handleProps: any = { ...props };
  if (!handleProps.pageSizeOptions) {
    handleProps.pageSizeOptions = [10, 20, 50, 100];
  }
  return (
    <SearchPageProvider
      src={props.src}
      noSearch={props.noSearch}
      searchForm={props.searchForm}
      onMount={props.onMount}
      uploadData={props.uploadData}
      defaultPageSize={props.defaultPageSize ?? handleProps.pageSizeOptions[0]}
      searchFormat={props.searchFormat}
      defaultFilters={props.defaultFilters}
      onSearchHandle={props.onSearchHandle}
      queryMutationParams={props.queryMutationParams}
    >
      <SearchPageCore {...handleProps} />
    </SearchPageProvider>
  );
};

const SearchPageCore: FC<Props> = ({
  children,
  breadcrumbList,
  defaultPageSize,
  pageSizeOptions,
}) => {
  const { replace } = useRouter();
  const { pagination, setPagination, query } = useSearchPageContext();
  const onSizeChange: PaginationProps["onChange"] = (page, pageSize) => {
    setPagination({
      current: page,
      pageSize,
    });
    setTimeout(() => query?.mutate?.(null));
  };

  const paginationWrapperClassName = "pb-[60px] relative";
  return (
    <div className="relative flex min-w-[1200px] flex-1 flex-col p-[20px] bg-blend-darken">
      <div className="flex items-center justify-between pr-[30px]">
        <BreadcrumbList list={breadcrumbList} />
        <Typography.Link
          onClick={(e) => {
            e.preventDefault();
            cleanToken();
            replace("/login").then();
          }}
        >
          登出
        </Typography.Link>
      </div>
      <Card
        className={classNames(
          "box-border flex-1 bg-[#fafafa] shadow-xl",
          paginationWrapperClassName
        )}
        bodyStyle={{ display: "flex", flexDirection: "column", height: "100%" }}
      >
        {children}
        <div className="absolute bottom-[20px] right-[30px]">
          <Pagination
            showSizeChanger
            defaultPageSize={defaultPageSize ?? pageSizeOptions![0]}
            onShowSizeChange={onSizeChange}
            onChange={onSizeChange}
            pageSizeOptions={pageSizeOptions}
            {...pagination}
          />
        </div>
      </Card>
    </div>
  );
};
SearchPage.Search = ({
  children,
  extraHeader,
  addLabel,
  onAddClick,
  actions,
  onHandleSearch,
  ...props
}) => {
  const { searchForm, query } = useSearchPageContext();
  return (
    <div>
      <Form form={searchForm} layout="inline" {...props}>
        {extraHeader}
        <Space size={[16, 16]} wrap>
          {children}
          <Button
            type="primary"
            size="small"
            onClick={() => {
              onHandleSearch?.()
              query?.mutate(null)
            }}
            className="my-[4px]"
          >
            搜索
          </Button>
          {onAddClick && (
            <Button
              type="primary"
              size="small"
              onClick={onAddClick}
              className="my-[4px] ml-[10px]"
            >
              {addLabel}
            </Button>
          )}
          {actions}
        </Space>
      </Form>
    </div>
  );
};

SearchPage.Cont = ({ children, className, style }) => {
  return (
    <div
      style={style}
      className={classNames(className, "mt-[30px] overflow-y-auto")}
    >
      {children}
    </div>
  );
};

export default SearchPage;
